package com.kudian.restful.service;

import com.kudian.common.persistence.HibernateDao;
import com.kudian.common.service.BaseService;
import com.kudian.common.utils.DateUtils;
import com.kudian.common.utils.StringUtils;
import com.kudian.restful.dao.*;
import com.kudian.restful.entity.*;
import com.kudian.restful.vo.ad.AdItemVO;
import com.kudian.restful.vo.ad.MidAdRetVO;
import com.kudian.restful.vo.ad.MidAdVO;
import com.kudian.restful.vo.message.*;
import org.apache.log4j.Logger;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/4/18.
 */
@Service
@Transactional(readOnly = true)
public class MessageService extends BaseService<Message, Integer> {
    private static final Logger logger = Logger.getLogger(MessageService.class);

    @Autowired
    private MessageDao messageDao;

    @Autowired
    private ReadMessageDao readMessageDao;

    @Autowired
    private LoginSessionDao loginSessionDao;

    @Autowired
    private UsersDao usersDao;

    @Autowired
    private MediaResService mediaResService;

    private final String sysPic = "30a5808ff80c429fa5ae5c0b15a7b88e";

    @Override
    public HibernateDao<Message, Integer> getEntityDao() {
        return messageDao;
    }

    public List<MsgItemVO> queryMsgsByself(@RequestBody QueryMsgVO vo) {
        LoginSession ent = loginSessionDao.get(vo.getAccess_token());
        if (ent == null) {
            return null;
        }

        List<MsgItemVO> ret = null;
        List<Message> ms = messageDao.findbyorder("sentTime", false,
                Restrictions.or(Restrictions.and(Restrictions.eq("senderId", 0), Restrictions.eq("receiverId", 0), Restrictions.eq("deleted", false))
                , Restrictions.and(Restrictions.eq("receiverId", ent.getUserId()), Restrictions.eq("deleted", false))));

        for (Message m : ms) {
            if (ret == null)
                ret = new ArrayList<MsgItemVO>();

            MsgItemVO item = new MsgItemVO();
            int senderId = m.getSenderId();
            int receiverId = m.getReceiverId();

            if (senderId == 0 && receiverId == 0) {
                ReadMessage rm = readMessageDao.findUnique(Restrictions.eq("messageId", m.getMessageId()), Restrictions.eq("userId", ent.getUserId()));
                if (rm == null) {
                    item.setReaded(false);
                    item.setDeleted(false);
                    item.setIsSys(true);
                } else {
                    item.setReaded(rm.getReaded());
                    item.setDeleted(rm.getDeleted());
                    item.setIsSys(true);
                }
            } else {
                item.setReaded(m.getReaded());
                item.setDeleted(m.getDeleted());
                item.setIsSys(false);
            }
            if (item.getDeleted()) {
                continue;
            }

            item.setSenderId(m.getSenderId());
            item.setReceiverId(ent.getUserId());
            item.setMessageId(m.getMessageId());
            item.setSentTime(m.getSentTime());
            item.setTitle(m.getTitle());
            item.setMsg(m.getMsg());

            if (item.getReceiverId() == null || item.getReceiverId().intValue() == 0) {
                item.setReceiverPic(this.mediaResService.getResUrl(sysPic));
            } else {
                Users u = this.usersDao.get(item.getReceiverId());
                if (u != null) {
                    item.setReceiverPic(this.mediaResService.getResUrl(u.getHeadPic()));
                }
            }
            if (item.getSenderId() == null || item.getSenderId().intValue() == 0) {
                item.setSenderPic(this.mediaResService.getResUrl(sysPic));
            } else {
                Users u = this.usersDao.get(item.getSenderId());
                if (u != null) {
                    item.setSenderPic(this.mediaResService.getResUrl(u.getHeadPic()));
                }
            }
            ret.add(item);
        }
        return ret;
    }

    @Transactional(readOnly = false)
    public MsgItemVO details(DetailMsgVO vo) {
        MsgItemVO info = null;
        LoginSession ent = loginSessionDao.get(vo.getAccess_token());
        if (ent == null) {
            return null;
        }
        Message m = messageDao.findUnique(Restrictions.or(Restrictions.eq("receiverId", ent.getUserId()), Restrictions.eq("receiverId", 0)),
                Restrictions.eq("messageId", vo.getMessageId()));
        if (m == null) {
            return null;
        }
        if (info == null) {
            info = new MsgItemVO();
        }

        int senderId = m.getSenderId();
        int receiverId = m.getReceiverId();

        if (senderId == 0 && receiverId == 0) {
            ReadMessage rm = readMessageDao.findUnique(Restrictions.eq("messageId", m.getMessageId()), Restrictions.eq("userId", ent.getUserId()));
            if (rm == null) {
                // 添加读标识
                ReadMessage rm1 = new ReadMessage();
                rm1.setMessageId(m.getMessageId());
                rm1.setUserId(ent.getUserId());
                rm1.setReaded(true);
                rm1.setReadTime(DateUtils.getSysTimestamp());
                rm1.setDeleted(false);
                this.readMessageDao.save(rm1);

                info.setReaded(true);
                info.setDeleted(false);
                info.setIsSys(true);
            } else {
                info.setReaded(rm.getReaded());
                info.setDeleted(rm.getDeleted());
                info.setIsSys(true);
            }
        } else {
            info.setReaded(m.getReaded());
            info.setDeleted(m.getDeleted());
            info.setIsSys(false);
        }

        info.setSenderId(m.getSenderId());
        info.setReceiverId(ent.getUserId());
        info.setMessageId(m.getMessageId());
        info.setSentTime(m.getSentTime());
        info.setTitle(m.getTitle());
        info.setMsg(m.getMsg());

        if (info.getReceiverId() == null || info.getReceiverId().intValue() == 0) {
            info.setReceiverPic(this.mediaResService.getResUrl(sysPic));
        } else {
            Users u = this.usersDao.get(info.getReceiverId());
            if (u != null) {
                info.setReceiverPic(this.mediaResService.getResUrl(u.getHeadPic()));
            }
        }
        if (info.getSenderId() == null || info.getSenderId().intValue() == 0) {
            info.setSenderPic(this.mediaResService.getResUrl(sysPic));
        } else {
            Users u = this.usersDao.get(info.getSenderId());
            if (u != null) {
                info.setSenderPic(this.mediaResService.getResUrl(u.getHeadPic()));
            }
        }
        return info;
    }

    @Transactional(readOnly = false)
    public void delete(DeleteMsgVO vo) {
        MsgItemVO info = null;
        LoginSession ent = loginSessionDao.get(vo.getAccess_token());
        if (ent == null) {
            return;
        }
        Message m = messageDao.findUnique(Restrictions.or(Restrictions.eq("receiverId", ent.getUserId()), Restrictions.eq("receiverId", 0)),
                Restrictions.eq("messageId", vo.getMessageId()));
        if (m == null) {
            return;
        }

        int senderId = m.getSenderId();
        int receiverId = m.getReceiverId();

        if (senderId == 0 && receiverId == 0) {
            ReadMessage rm = readMessageDao.findUnique(Restrictions.eq("messageId", m.getMessageId()), Restrictions.eq("userId", ent.getUserId()));
            if (rm != null) {
                rm.setDeleted(true);
                this.readMessageDao.save(rm);
            } else {
                rm = new ReadMessage();

                rm.setMessageId(m.getMessageId());
                rm.setUserId(ent.getUserId());
                rm.setReaded(true);
                rm.setReadTime(DateUtils.getSysTimestamp());
                rm.setDeleted(true);
                readMessageDao.save(rm);
            }
        } else {
            m.setDeleted(true);
            this.messageDao.save(m);
        }
    }
}
